/*
 * The idea is that generated hash code should be the same as we have in 
 * collections.json; so we can compare hash code one by one and detect book 
 * title etc.
 */
package com.vs.kindlecoll.IO;

import com.vs.kindlecoll.Beans.Book;
import com.vs.kindlecoll.Beans.BooksCollection;
import com.vs.kindlecoll.UI.UIHelper;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTree;

//import org.junit.experimental.theories.PotentialAssignment.CouldNotGenerateValueException;

/**
 *
 * @author volodymyr.sadovyy
 */
public class BookHashIniter implements Runnable {

    JTree tree;

    public BookHashIniter(JTree jTreeCollections) {
        tree = jTreeCollections;
    }

    public void run() {
        if (null == KindleInteractor.books
                || null == KindleInteractor.colls) {
            return;
        }
        //go over collections
        int count = 0;
        for (BooksCollection c : KindleInteractor.colls) {
            //go over books in collections
            for (Book bookInColls : c.getBooks()) {
                boolean found = false;
                //go over books on the disk
                for (Book bookInList : KindleInteractor.books) {
                    //TODO: for now lets go with indexOf, later we should use eq.
                    //if(bookInList.getKindleHash().equalsIgnoreCase(bookInColls.getKindleHash())){
                    if (bookInColls.getKindleHash().equalsIgnoreCase(bookInList.getKindleHash())) {
                        bookInColls.setLocation(bookInList.getLocation());
                        bookInColls.setTitle(bookInList.getTitle());
                        //break the loop in case we found this book
                        found = true; count++;
                        bookInList.addCollection(c);
                        break;
                    }
                }
                //TODO:Remove or hightlight book from collections in case we cannot detect it.
                if (!found) {
                    Logger.getLogger(BookHashIniter.class.getName()).log(Level.INFO,
                            "Book should be hidden: {0} in collection: {1}", new Object[]{bookInColls, c});
                }
            }

        }
        Logger.getLogger(BookHashIniter.class.getName()).log(Level.INFO,
                "{0} Books were skipped", count);
        if (null != tree) {
            UIHelper ui = new UIHelper();
            ui.updateTreeModel(tree);
        }

    }
}
